//
//  LSStatusListViewModel.swift
//  新浪微博---01次
//
//  Created by 李宗帅 on 16/5/6.
//  Copyright © 2016年 LS. All rights reserved.
//

import UIKit
import SDWebImage
//ViewModel需要做的事情
//1>网络请求类
//2>需要和model关联
class LSStatusListViewModel: NSObject {

    static let shareInstance:LSStatusListViewModel = LSStatusListViewModel()
    
    //懒加载初始化模型数组
    lazy var statusList :[LSStatusViewModel] = [LSStatusViewModel]()
    
    private override init() {
        
    }
    
    func loadData(since_id: Int = 0,max_id: Int = 0,succe:(count:Int) ->(),failed:(error:NSError) -> ()){
        let url = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        //对可选项进行解包
        guard let token = LSOauthViewModel.shareInstance.access_token else {
            return
        }
        
        //since_ID 和MAX_id  默认都是0 
        let params = ["access_token": token,
            "since_id":since_id,
            "max_id":max_id]
        
        //新建一个组
        let guoup = dispatch_group_create()
        
        var count = 0
        
        LSHTTPClicent.shareInstance.request(.GET, URLString: url, parameters: params, success: { (_, JSON) -> Void in
            
            printLog(JSON)
            
            // 需要对数据进行解析,
            if let json = JSON as? [String: AnyObject] {
                // 1. 先拿到statues
                if let statues = json["statuses"] as? [[String: AnyObject]]{
        
                    var temp = [LSStatusViewModel]()
                    
                    // 一个可选的数据，不能进行遍历
                    // 2. 对数组进行一个遍历
                    for status in  statues{
                        
                        // 3.字典转模型
                        let model = LSStatus(dic: status)
                        
                        let statusViewModel = LSStatusViewModel(model: model)
                        
                        //数据下载好之后,就判断一下是否是一张图片
                        if let pic_urls = statusViewModel.retweet_pic_urls == nil ?
                            statusViewModel.status?.pic_urls : statusViewModel.retweet_pic_urls where pic_urls.count == 1 {
                                //进入组
                                dispatch_group_enter(guoup)
                                
                                //下载一张图片
                                //有两种形式 1.种 自己实现以下 2.借助SDWebImage
                                SDWebImageManager.sharedManager().downloadImageWithURL(pic_urls.first?.thumbnail_pic, options: [], progress: nil, completed: { (image, _, _, _, _) -> Void in
                                    
//                                    
//                                     let data = UIImagePNGRepresentation(image)
//                                    
//                                    
                                    //完成之后 离开组
                                    dispatch_group_leave(guoup)
                                    
                                })
                        }
                        
                        // 数组添加数据
                        temp.append(statusViewModel)
                        
                       
                    }
                    //对刷新后的数据 拼接到statuslist
                    if max_id > 0 {
                        self.statusList = self.statusList + temp
                    } else {
                        self.statusList = temp + self.statusList
                    }
                    
                    count = temp.count
                }
            }
         
            //组里的异步线程都完成之后 进行回调
            dispatch_group_notify(guoup, dispatch_get_main_queue(), { () -> Void in
                
                // 解析完成之后，告诉控制器，刷新数据
                succe(count: count)
                
            })
            
            
            }) { (_ , error) -> Void in
                printLog(error)
                
                failed(error: error)
        }
    }

}
